package com.djmw.mouse.web.member;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.validation.Validator;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.djmw.mouse.entity.Application;
import com.djmw.mouse.entity.Bookmark;
import com.djmw.mouse.entity.BookmarkId;
import com.djmw.mouse.entity.Cv;
import com.djmw.mouse.entity.MemberUser;
import com.djmw.mouse.entity.Position;
import com.djmw.mouse.service.ApplicationService;
import com.djmw.mouse.service.BookmarkService;
import com.djmw.mouse.service.CvService;
import com.djmw.mouse.service.PositionService;
import com.djmw.mouse.service.account.ShiroDbRealm.ShiroUser;
import com.google.common.collect.Maps;

/**
 * 投递管理的Controller, 使用Restful风格的Urls:
 * 
 * 列表: GET /member/application <br>
 * 投递 : POST /member/application/post <br>
 * 
 * @author michael
 */

@Controller
@RequestMapping(value = "/member/application")
public class ApplicationController {

    private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
    static {
        sortTypes.put("auto", "申请日期");
    }

    @Autowired
    private PositionService positionService;
    @Autowired
    private CvService cvService;
    @Autowired
    private BookmarkService bookmarkService;
    @Autowired
    private ApplicationService applicationService;
    // @Autowired
    // private MemberAccountService memberAccountService;
    @Autowired
    private Validator validator;

    @RequestMapping(value = "")
    public String list(Model model, ServletRequest request) {
        MemberUser user = getCurrentUser();
        Page<Application> applications = applicationService.getApplicationByMemberUserId(user.getId(), 1, 20);
        model.addAttribute("applications", applications);
        model.addAttribute("sortType", "auto");
        model.addAttribute("sortTypes", sortTypes);
        // Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return "member/application-list";
    }

    @RequestMapping(value = "post", method = RequestMethod.POST)
    public String apply(@RequestParam("pid") Long positionId, RedirectAttributes redirectAttributes) {
        MemberUser user = getCurrentUser();
        if (user.getProfileCompletion() < 60) {
            Position position = positionService.getPosition(positionId);
            if (position != null) {
                Bookmark bm2 = bookmarkService.findExistingPositionBookmark(position, user);
                if (bm2 == null) {
                    Bookmark bookmark = new Bookmark();
                    bookmark.setPosition(position);
                    bookmark.setMemberUser(user);
                    bookmark.setType(BookmarkId.BOOKMARK_TYPE_POSITION);
                    bookmark.setCreateDate(new Date());
                    position.getBookmark().add(bookmark);
                    positionService.savePosition(position, null);
                }
            }
            redirectAttributes.addFlashAttribute("message", "个人信息不完整，请填写完整后继续投递。已为您保存该职位。");
            return "redirect:/member/profile/edit";
        }
        List<Cv> cvList = cvService.getMemberCvList(user.getId(), true);
        if (cvList.size() == 0) {
            redirectAttributes.addFlashAttribute("message", "没有可供投递的简历");
            return "redirect:/jobsearch/position/" + positionId;
        }
        Cv cv = null;
        for (int i = 0; i < cvList.size(); i++) {
            if (cvList.get(i).getStatus() == Cv.STATUS_ENABLED && cvList.get(i).getCvLang().size() > 0) {
                cv = cvList.get(i);
                break;
            }
        }
        if (cv == null) {
            redirectAttributes.addFlashAttribute("message", "没有可供投递的简历");
            return "redirect:/jobsearch/position/" + positionId;
        }
        Position position = positionService.getPosition(positionId);
        Application application = new Application();
        application.setPosition(position);
        application.setCvLang(cv.getCvLang().get(0));
        application.setMemberUser(user);
        application.setCreateDate(new Date());
        Application app2 = applicationService.findExistingApplication(position, cv.getCvLang().get(0), user);
        if (app2 != null) {
            redirectAttributes.addFlashAttribute("message", "已经投递过此职位");
            return "redirect:/jobsearch/position/" + positionId;
        }
        position.getApplication().add(application);
        positionService.savePosition(position, null);
        redirectAttributes.addFlashAttribute("message", "申请成功");
        return "redirect:/jobsearch/position/" + positionId;
    }

    public MemberUser getCurrentUser() {
        ShiroUser user = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
        MemberUser memberUser = (MemberUser) user.getUser();
        return memberUser;
    }
}
